package anveshitha.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;

import anveshitha.analyzers.JavaSourceCodeAnalyzer;
import anveshitha.query.QueryExecutor;
import anveshitha.query.QueryResult;

/**
 * Servlet implementation class for Servlet: ExecuteQueryServlet
 *
 */
public class ExecuteQueryServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(ExecuteQueryServlet.class);

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ExecuteQueryServlet() {
		super();
	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		//TODO: check query string
		String language = request.getParameter("selLanguage");
		String query = request.getParameter("textQuery");

		QueryExecutor queryExecutor = new QueryExecutor(language,
				new JavaSourceCodeAnalyzer());

		//get results and store in request
		try {
			List<QueryResult> results = queryExecutor.execute(query,false);
			request.setAttribute("queryResults", results);
		} catch (ParseException e) {
			log.error(e.getMessage());
			request.setAttribute("error", "Error while executing query.");
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/results.jsp");
		dispatcher.forward(request, response);

	}
}